﻿<%@ WebHandler Language="C#" Class="RbRepairContainerStartHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Web.SessionState;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using DatabaseAccess.DBUtility;
using System.Text;
/*Description: 热表返修批次开卡处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20240606
'Rewriter:
'Rewrite Date:
*/
public class RbRepairContainerStartHandler : IHttpHandler, IRequiresSessionState
{
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private RbContainerBusiness m_RbContianer = new RbContainerBusiness();
    private uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    private static object thisLock = new object();
    CurrentUserInfo m_UserInfo;
    string rbFactoryID = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"].ToString(); //热表ID

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            string action = context.Request["action"].ToString();
            switch (action)
            {
                case "StartReContainer"://开卡
                    lock (thisLock)
                    {
                        StartReContainer(context);
                    }
                    break;
                case "GetNeedRepairContainerList"://获取需要返修的批次列表
                    GetNeedRepairContainerList(context);
                    break;
                case "GetRepairContainerList"://获取已返修批次列表
                    GetRepairContainerList(context);
                    break;
                case "GetRepairContainerStartInfo"://获取返修开卡需要的数据信息
                    GetRepairContainerStartInfo(context);
                    break;
                case "GetWorkFlowListDatas"://获取工艺信息
                    GetWorkFlowListDatas(context);
                    break;
                case "GetStepListDatas"://获取工序信息
                    GetStepListDatas(context);
                    break;
                case "GetStepInfoList"://获取工步信息
                    GetStepInfoList(context);
                    break;
                case "GetTeams"://获取班组
                    GetTeams(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未知功能" }));
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = string.Format("功能出错：{0}", e.Message) }));
        }
    }

    /// <summary>
    /// 获取可开返修的批次数据
    /// </summary>
    /// <param name="context"></param>
    private void GetNeedRepairContainerList(HttpContext context)
    {
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT c.mfgordername,c.mfgorderid,c.productid,c.productname,c.productrevision,c.containerid,c.containername,c.qty,
                            s.stepinfoid,s.stepno,s.description stepname,cci.reworkqty,c.containertype
                            FROM containercurrentinfo c
                            INNER JOIN containercheckinfo2 cci ON cci.containerid = c.containerid AND NVL(cci.reworkqty,0) <> 0 AND cci.isuse = 0
                            LEFT JOIN stepinfo s ON s.stepinfoid = cci.stepinfoid
                            LEFT JOIN Userattribute u ON u.userattributename = '返修批次工步' AND u.attributevalue = c.containerid || cci.stepinfoid
                            LEFT JOIN container subc ON subc.containerid = u.parentid AND subc.status != 0 --返修子卡
                            WHERE c.originalfactoryid = '{0}' 
                            AND c.isinstore = 0 
                            AND c.containerstatus = 1  
                            AND subc.containerid IS NULL", rbFactoryID);
        //查询订单号
        if (param.ContainsKey("mfgOrderName") && !string.IsNullOrWhiteSpace(param["mfgOrderName"]))
        {
            sql.AppendFormat(" AND c.mfgordername like '%{0}%'", param["mfgOrderName"]);
        }
        //查询件号
        if (param.ContainsKey("productName") && !string.IsNullOrWhiteSpace(param["productName"]))
        {
            sql.AppendFormat(" AND c.productname like '%{0}%'", param["productName"]);
        }
        //查询批次号
        if (param.ContainsKey("containerName") && !string.IsNullOrWhiteSpace(param["containerName"]))
        {
            sql.AppendFormat(" AND c.containername LIKE '%{0}%'", param["containerName"]);
        }
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(param["pageIndex"]);
        pageDto.PageSize = int.Parse(param["pageSize"]);
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取已返修批次数据
    /// </summary>
    /// <param name="context"></param>
    private void GetRepairContainerList(HttpContext context)
    {
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT c.mfgordername,c.productname,c.containername,c.originalstartdate startdate,c.qty,s.stepno,s.description stepname,fc.containername facontainername
                            FROM containercurrentinfo c
                            INNER JOIN Userattribute u ON u.parentid = c.containerid AND u.userattributename = '返修主批次ID'
                            LEFT JOIN containercurrentinfo fc ON fc.containerid = u.attributevalue
                            INNER JOIN Userattribute uu ON uu.parentid = c.containerid AND uu.userattributename = '返修工步ID'
                            LEFT JOIN stepinfo s ON s.stepinfoid = uu.attributevalue
                            WHERE c.originalfactoryid = '{0}' 
                            AND c.isinstore = 0 
                            AND c.containerstatus = 1 ", rbFactoryID);
        //查询订单号
        if (param.ContainsKey("mfgOrderName") && !string.IsNullOrWhiteSpace(param["mfgOrderName"]))
        {
            sql.AppendFormat(" AND c.mfgordername like '%{0}%'", param["mfgOrderName"]);
        }
        //查询件号
        if (param.ContainsKey("productName") && !string.IsNullOrWhiteSpace(param["productName"]))
        {
            sql.AppendFormat(" AND c.productname like '%{0}%'", param["productName"]);
        }
        //查询批次号
        if (param.ContainsKey("containerName") && !string.IsNullOrWhiteSpace(param["containerName"]))
        {
            sql.AppendFormat(" AND c.containername LIKE '%{0}%'", param["containerName"]);
        }
        //查询返修批次开卡时间
        if (param.ContainsKey("startDate") && !string.IsNullOrWhiteSpace(param["startDate"]))
        {
            sql.AppendFormat(" AND c.originalstartdate >= to_date('{0} 00:00:00','yyyy-mm-dd hh24:mi:ss') AND c.originalstartdate <= to_date('{0} 23:59:59','yyyy-mm-dd hh24:mi:ss')", param["startDate"]);
        }
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(param["pageIndex"]);
        pageDto.PageSize = int.Parse(param["pageSize"]);
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取返修开卡需要的数据信息
    /// </summary>
    /// <param name="context"></param>
    private void GetRepairContainerStartInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["selectedData"].ToString());
        //获取件号下拉数据
        DataTable subSectionProduct = m_CommonObj.GetSubsectionProductInfo(param["PRODUCTNAME"], param["PRODUCTID"]);
        DataTable subSectionProduct_dt = subSectionProduct.DefaultView.ToTable(false, new string[] { "productname", "productid" });
        DataRow subSectionProduct_dr = subSectionProduct_dt.NewRow();
        subSectionProduct_dr["productname"] = param["PRODUCTNAME"] + ":" + param["PRODUCTREVISION"];
        subSectionProduct_dr["productid"] = param["PRODUCTID"];
        subSectionProduct_dt.Rows.InsertAt(subSectionProduct_dr, 0);//将默认的版本放入第一行
        subSectionProduct_dt.TableName = "subSectionProductDt";
        result.DBDataSet.Tables.Add(subSectionProduct_dt);
        //获取工艺路线下拉数据
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductName", param["PRODUCTNAME"]);
        para.Add("ProductID", param["PRODUCTID"]);
        para.Add("ProductRev", param["PRODUCTREVISION"]);
        para.Add("FactoryID", m_UserInfo.FactoryID);
        DataTable wfdata = m_CommonObj.GetWorkflowInfoWithOtherAndSubByProductInfo(para, false, true);
        wfdata.TableName = "sectionWorkFlowDt";
        result.DBDataSet.Tables.Add(wfdata);
        //如果批次是批量子序号，查询出子序号
        if (param["CONTAINERTYPE"] == "3")
        {
            DataTable dtChildCon = DatabaseHelper.Query_ReturnDatTable(string.Format("SELECT c.containername,c.qualificationnum FROM container c WHERE c.parentcontainerid = '{0}' AND c.status = 1", param["CONTAINERID"]));
            dtChildCon.TableName = "dtChildCon";
            result.DBDataSet.Tables.Add(dtChildCon);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 动态获取工艺
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkFlowListDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string productinfo = context.Request.Form["productName"].ToString();
        DataTable wfdata = new DataTable();
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ProductName"] = productinfo.Substring(0, productinfo.IndexOf(":"));
        para["ProductRev"] = productinfo.Substring(productinfo.IndexOf(":") + 1);
        para["FactoryID"] = m_UserInfo.FactoryID;
        wfdata = m_CommonObj.GetWorkflowInfoWithOtherAndSubByProductInfo(para, false, true);
        if (wfdata.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "件号没有关联工艺", Result = false }));
            return;
        }
        int index = 0;
        foreach (DataRow item in wfdata.Rows)
        {
            if (!string.IsNullOrWhiteSpace(item["WorkflowID"].ToString()) && !string.IsNullOrWhiteSpace(item["WorkflowName"].ToString()))
            {
                continue;
            }
            else
            {
                index += 1;
            }
            if (index == wfdata.Rows.Count)
            {
                result.Result = false;
                result.Message = "件号关联的工艺信息不完善";
                break;
            }
        }
        if (result.Result)
        {
            result.DBTable = wfdata;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));

    }

    /// <summary>
    /// 动态获取工序下拉列表
    /// </summary>
    /// <param name="context"></param>
    public void GetStepListDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string workFlowID = context.Request.Form["workFlowID"].ToString();
        DataTable stepTable = m_CommonObj.GetWorkFlowSetpsByWorkflowID(workFlowID);//获取工序列表
        if (stepTable.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "没有工序数据";
        }
        if (result.Result)
        {
            //开始做工序验证
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("WorkflowID", workFlowID);
            para.Add("ChildWorkflow", "1");
            para.Add("GetFactoryValue", "");
            string childerStepIDs = "";//子工艺工序IDs  
            DataTable childwrokflowdt = m_CommonObj.GetWorkFlowSetpsDetailByWorkflowID(para);//获取子工艺
            childwrokflowdt.Columns.Add("CHILDWORKFLOW");
            foreach (DataRow r in childwrokflowdt.Rows)
            {
                if (r["WORKFLOWNAME"].ToString().Contains("空子工艺"))
                {
                    if (childwrokflowdt.Columns.Contains("factoryvalue"))
                    {
                        if (r["factoryvalue"].ToString() == "是")
                        {
                            result.Result = false;
                            result.Message = "子工艺为空子工艺，不允许开卡";
                            break;
                        }
                    }
                }
                childerStepIDs += r["WORKFLOWSTEPID"].ToString() + "，";
                r["CHILDWORKFLOW"] = r["WORKFLOWSTEPNAME"].ToString() + "(" + r["WORKFLOWNAME"].ToString() + ")";
            }
            if (result.Result)
            {
                childerStepIDs = childerStepIDs.Trim('，');
                string strValue_ = m_CommonObj.GetFatoryAttributes(m_UserInfo.FactoryID, "工序关联工区班组"); //获取工厂是否多人派工 燃烧不修改不可以派给其他班组
                if (strValue_ == "是")
                {
                    DataTable dt_ = m_CommonObj.GetWorkFlowStepsWithSpceControlCodeAndCheckStep(workFlowID, m_UserInfo.FactoryID); //获取固定转工固定外委以及检验序工序
                    string NotthisFactoryStepIDs = "";//不用检验的工序，即固定外委或固定转工的工序  
                    foreach (DataRow dr in dt_.Rows)
                    {
                        NotthisFactoryStepIDs += dr["WORKFLOWSTEPID"].ToString() + "，";
                    }
                    NotthisFactoryStepIDs = NotthisFactoryStepIDs.Trim('，');
                    foreach (DataRow item in stepTable.Rows)
                    {
                        if (NotthisFactoryStepIDs.Contains(item["WORKFLOWSTEPID"].ToString()) || childerStepIDs.Contains(item["WORKFLOWSTEPID"].ToString()))
                        {
                            continue;
                        }
                        else
                        {
                            if (!stepTable.Columns.Contains("WORKCENTERID") || string.IsNullOrWhiteSpace(item["WORKCENTERID"].ToString()))
                            {
                                result.Result = false;
                                result.Message = "工序 " + item["WORKFLOWSTEPNAME"].ToString() + " 的工区信息没有维护";
                                break;
                            }
                        }
                    }
                }
            }
            if (result.Result)
            {
                result.DBTable = stepTable;
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 动态获取班组下拉数据
    /// </summary>
    /// <param name="context"></param>
    public void GetTeams(HttpContext context)
    {
        DataTable dt_team = m_CommonObj.GetTeam(context.Request.Form["workcenterID"].ToString());
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult { Result = true, DBTable = dt_team }));
    }

    /// <summary>
    /// 动态获取工步下拉数据
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoList(HttpContext context)
    {
        string workflowStepID = context.Request.Form["workflowStepId"].ToString();
        DataTable dtSubWorkflow = GetSubWorkflowInfo(workflowStepID);//查询工序下的通用子工艺
        if (dtSubWorkflow.Rows.Count > 0) //如果存在通用子工艺，则取第三层的工序
        {
            workflowStepID = dtSubWorkflow.Rows[0]["workflowstepId"].ToString();
        }
        string sql = "SELECT s.stepinfoid,s.stepno || '-' || s.description stepdesc FROM stepinfo s WHERE s.workflowstepid = '{0}' ORDER BY s.stepseq";
        DataTable dt_StepInfo = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, workflowStepID));
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult { Result = true, DBTable = dt_StepInfo }));
    }

    /// <summary>
    /// 开返修卡
    /// </summary>
    /// <param name="context"></param>
    private void StartReContainer(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dtPageParams = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtPageParams.Rows.Count == 0)
        {
            result.Message = "数据过期，请重新填写";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataTable dtChildCon = JsonConvert.DeserializeObject<DataTable>(context.Request["childContainer"].ToString());
        DataRow drPageDatas = dtPageParams.Rows[0];//页面填写的数据内容
        string sql = string.Format(@"SELECT cci.containerid,cci.containername,cci.mfgordername,cci.techniqueemployeeid,e.employeename techniqueemployeename,cci.plannedstartdate,cci.plannedcompletiondate,cci.containertype,
                                     c.uomid,u.uomname,c.militarytype,c.rbcontainertype,c.rbtogetherflag,c.mfgbatch,cci.familylistnames,cci.workcentername,t.teamname,c.containercomments
                                     FROM containercurrentinfo cci
                                     LEFT JOIN container c ON c.containerid = cci.containerid
                                     LEFT JOIN team t ON t.teamid = c.teamid
                                     LEFT JOIN uom u ON u.uomid = c.uomid
                                     LEFT JOIN employee e ON e.employeeid = cci.techniqueemployeeid                                                                           
                                     WHERE cci.containername = '{0}'", drPageDatas["faContainerName"].ToString());
        DataTable dtFaCon = DatabaseHelper.Query_ReturnDatTable(sql);
        DataRow drFc = dtFaCon.Rows[0];//返修主批次的信息
        if (drFc["containertype"].ToString() == "3" && dtChildCon.Rows.Count != int.Parse(drPageDatas["qty"].ToString()))
        {
            result.Message = "请选择对应数量的子序号";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        /*开始赋值批次属性*/
        ContainerStartInfo containerBaseInfo = new ContainerStartInfo();
        containerBaseInfo.ContainerName = CreateFxContainerName(drPageDatas["faContainerName"].ToString());//批次名（返修批次_F_顺序号）
        containerBaseInfo.Qty = drPageDatas["qty"].ToString();//批次数量（返修数量）
        containerBaseInfo.MfgOrder = drFc["mfgordername"].ToString();//订单
        containerBaseInfo.MonthPlan = "";//月度计划
        FillContainerDefaultInfo(ref containerBaseInfo, m_UserInfo.FactoryID);
        containerBaseInfo.TogetherFlag = containerBaseInfo.ContainerName;//大批次 = 批次名
        containerBaseInfo.Factory = m_UserInfo.Factory;//批次分厂
        containerBaseInfo.CheckTechnique = drFc["techniqueemployeename"].ToString();//工艺员
        containerBaseInfo.UOM = drFc["uomname"].ToString();//单位
        containerBaseInfo.WorkCenter = drFc["workcentername"].ToString();//工区
        containerBaseInfo.Team = drFc["teamname"].ToString();//班组
        containerBaseInfo.StartEmployee = m_UserInfo.EmployeeName;//开卡人

        string product = drPageDatas["productName"].ToString();
        containerBaseInfo.ProductName = product.Substring(0, product.IndexOf(":"));
        containerBaseInfo.ProductRevision = product.Substring(product.IndexOf(":") + 1);
        containerBaseInfo.ProductuseROR = false;
        /*赋值工艺信息*/
        string workflowName = drPageDatas["WorkflowName"].ToString();
        string startWorkflowStep = drPageDatas["startWorkflowStep"].ToString();
        DataTable dtSubWorkflow = GetSubWorkflowInfo(startWorkflowStep);//查询工序下的通用子工艺，存在，则替换为子工艺
        if (dtSubWorkflow.Rows.Count > 0)
        {
            DataRow drsub = dtSubWorkflow.Rows[0];
            containerBaseInfo.BeginStep = drsub["workflowstepname"].ToString();
            containerBaseInfo.MfgWorkflowName = drsub["workflowname"].ToString();
            containerBaseInfo.MfgWorkflowRevision = drsub["workflowrevision"].ToString();
            containerBaseInfo.MfgWorkflowuseROR = false;
            containerBaseInfo.WorkflowName = drsub["workflowname"].ToString();
            containerBaseInfo.WorkflowRevision = drsub["workflowrevision"].ToString();
            containerBaseInfo.WorkflowuseROR = false;
        }
        else
        {
            containerBaseInfo.BeginStep = drPageDatas["startWorkflowStepName"].ToString();
            containerBaseInfo.MfgWorkflowName = workflowName.Substring(0, workflowName.IndexOf(":"));
            containerBaseInfo.MfgWorkflowRevision = workflowName.Substring(workflowName.IndexOf(":") + 1, workflowName.LastIndexOf("(") - workflowName.IndexOf(":") - 1);
            containerBaseInfo.MfgWorkflowuseROR = false;
            containerBaseInfo.WorkflowName = containerBaseInfo.MfgWorkflowName;
            containerBaseInfo.WorkflowRevision = containerBaseInfo.MfgWorkflowRevision;
            containerBaseInfo.WorkflowuseROR = false;
        }
        containerBaseInfo.Comment = string.Format("{0},{1}", drFc["containercomments"].ToString(), drPageDatas["notes"].ToString().Trim());//备注（继承主卡批次备注以及页面填写的备注）
        containerBaseInfo.PlannedStartDate = DateTime.Parse(drFc["plannedstartdate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.PlannedCompletionDate = DateTime.Parse(drFc["plannedcompletiondate"].ToString()).ToString("yyyy-MM-ddTHH:mm:ss");
        containerBaseInfo.ContainerType = drFc["containertype"].ToString();
        containerBaseInfo.MilitaryType = drFc["militarytype"].ToString();
        containerBaseInfo.QualificationQty = "1";
        containerBaseInfo.RbTogetherflag = drFc["rbtogetherflag"].ToString();
        containerBaseInfo.RbContainerType = drFc["rbcontainertype"].ToString();
        ServerHostInfo serverInfo = new ServerHostInfo();
        serverInfo.UserName = m_UserInfo.APIUserName;
        serverInfo.Password = m_UserInfo.APIPassword;
        containerBaseInfo.ServerHostInfo = serverInfo;
        //填充机型
        string[] strFamily = drFc["familylistnames"].ToString().Split(' ');
        Dictionary<int, string> listFamily = new Dictionary<int, string>();
        for (int i = 0; i < strFamily.Length; i++)
        {
            listFamily.Add(i + 1, strFamily[i]);
        }
        containerBaseInfo.MfgBatch = drFc["mfgbatch"].ToString();
        containerBaseInfo.ProductFamilyList = listFamily;
        //扩展属性
        containerBaseInfo.AttributeList = AddContainerAttribute(containerBaseInfo, drFc, drPageDatas, dtSubWorkflow.Rows.Count > 0 ? true : false);
        if (drFc["containertype"].ToString() == "3")
        {
            //子序号赋值
            DataTable childDt = new DataTable();
            childDt.Columns.Add("ContainerName");
            childDt.Columns.Add("Qty");
            childDt.Columns.Add("ChildBeginStep");
            childDt.Columns.Add("TogetherFlag");
            childDt.Columns.Add("QualificationNum");
            childDt.Columns.Add("RbContainerType");
            foreach (DataRow item in dtChildCon.Rows)
            {
                DataRow childRow = childDt.NewRow();
                childRow["ContainerName"] = containerBaseInfo.ContainerName + item["qualificationnum"].ToString();
                childRow["Qty"] = 1;
                childRow["ChildBeginStep"] = drPageDatas["startWorkflowStepName"].ToString();
                childRow["TogetherFlag"] = containerBaseInfo.TogetherFlag;
                childRow["QualificationNum"] = item["qualificationnum"].ToString();
                childRow["RbContainerType"] = containerBaseInfo.RbContainerType;
                childDt.Rows.Add(childRow);
            }
            containerBaseInfo.ChildList = childDt;
        }
        //开卡
        ResultStatus res = m_ContainerObj.StartContainer(containerBaseInfo);
        if (res.IsError)
        {
            result.Result = false; result.Message = res.Message.ToString().Replace("Container", "批次：").Replace("already exists", "已存在");
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        result.Result = true; result.Message = "批次创建成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 生成批次名
    /// </summary>
    /// <param name="containerName"></param>
    /// <returns></returns>
    private string CreateFxContainerName(string containerName)
    {
        string sql = string.Format("SELECT cci.containername FROM containercurrentinfo cci WHERE cci.containername LIKE '{0}_F%'", containerName);
        DataTable dtCon = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtCon.Rows.Count == 0)
        {
            return string.Format("{0}_F01", containerName);
        }
        int cNo;
        List<int> conNo = new List<int>();
        foreach (DataRow item in dtCon.Rows)
        {
            if (int.TryParse(item["containername"].ToString().Replace(string.Format("{0}_F", containerName), ""), out cNo))
            {
                conNo.Add(cNo);
            }
        }
        return string.Format("{0}_F{1}", containerName, (conNo.Max() + 1).ToString().PadLeft(2, '0'));
    }

    /// <summary>
    /// 获取通用子工艺信息
    /// </summary>
    /// <param name="faWorkFlowStepID">父工序ID</param>
    /// <returns></returns>
    private DataTable GetSubWorkflowInfo(string faWorkFlowStepID)
    {
        string sql = string.Format(@"SELECT swb.workflowname,w.workflowrevision,sws.workflowstepname,sws.workflowstepid
                    FROM workflowstep ws 
                    LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                    LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                    INNER JOIN workflow w ON w.process_no = s.commonsubworkflow
                    INNER JOIN workflowbase swb on swb.revofrcdid=w.workflowid
                    LEFT JOIN workflowstep sws ON sws.workflowid = w.workflowid
                    WHERE ws.workflowstepid = '{0}'", faWorkFlowStepID);
        return DatabaseHelper.Query_ReturnDatTable(sql);
    }

    /// <summary>
    /// 填充批次默认信息
    /// </summary>
    /// <param name="containerBaseInfo"></param>
    /// <param name="factoryId"></param>
    private void FillContainerDefaultInfo(ref ContainerStartInfo containerBaseInfo, string factoryId)
    {
        DataTable levelAttributes = m_CommonObj.GetFatoryAttributes(factoryId);
        DataRow[] datarows = levelAttributes.Select("USERATTRIBUTENAME='默认所有者'");
        string strOwner = "";
        if (datarows.Length > 0)
        {
            strOwner = datarows[0]["ATTRIBUTEVALUE"].ToString();
        }
        datarows = levelAttributes.Select("USERATTRIBUTENAME='默认层级'");
        string strLevel = "";
        if (datarows.Length > 0)
        {
            strLevel = datarows[0]["ATTRIBUTEVALUE"].ToString();
        }
        string strStart = "";
        if (string.IsNullOrWhiteSpace(containerBaseInfo.MfgOrder.ToString()))
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='无订单开始原因'");
        }
        else
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='订单开始原因'");
        }
        if (datarows.Length > 0)
        {
            strStart = datarows[0]["ATTRIBUTEVALUE"].ToString();
        }

        containerBaseInfo.StartReason = strStart;
        containerBaseInfo.Level = strLevel;
        containerBaseInfo.Owner = strOwner;
        string test = containerBaseInfo.IsSelfMfg.ToString();
        if (containerBaseInfo.IsSelfMfg.ToString() == "True")
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='自投料流程'");
        }
        else
        {
            datarows = levelAttributes.Select("USERATTRIBUTENAME='领料流程'");
        }
        if (datarows.Length > 0)
        {
            string[] strWorkflows = datarows[0]["ATTRIBUTEVALUE"].ToString().Split('：');
            containerBaseInfo.WorkflowName = strWorkflows.First();
            containerBaseInfo.WorkflowRevision = strWorkflows.Last();
            containerBaseInfo.WorkflowuseROR = false;
        }
    }

    /// <summary>
    /// 添加流水卡扩展属性
    /// </summary>
    /// <param name="containerInfo">批次信息</param>
    /// <param name="drFc">返修批次信息</param>
    /// <param name="drPage">页面填写信息</param>
    /// <param name="isSub">是否有子工艺</param>
    /// <returns></returns>
    private DataTable AddContainerAttribute(ContainerStartInfo containerInfo, DataRow drFc, DataRow drPage, bool isSub)
    {
        DataTable attributeDt = new DataTable();
        attributeDt.Columns.Add("ContainerName");
        attributeDt.Columns.Add("Level");
        attributeDt.Columns.Add("Name");
        attributeDt.Columns.Add("Value");
        /*工艺员*/
        DataRow row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "CheckTechnique";
        row["Value"] = containerInfo.CheckTechnique.ToString();
        attributeDt.Rows.Add(row);
        /*开始工序*/
        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "BeginStep";
        row["Value"] = containerInfo.BeginStep.ToString();
        attributeDt.Rows.Add(row);
        /*存储开始工步的所有信息（不能存开始工步的ID，因为可能生产时用的是新版工步）*/
        string sql = string.Format("SELECT s.stepseq FROM stepinfo s WHERE s.stepinfoid = '{0}'", drPage["startStepInfoID"].ToString());
        DataTable dtStep = DatabaseHelper.Query_ReturnDatTable(sql);
        /*开始工步顺序号*/
        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "开始工步顺序号";
        row["Value"] = dtStep.Rows[0]["stepseq"].ToString();
        attributeDt.Rows.Add(row);
        /*返修批次工步（可作为唯一标识，一个批次的一个工步只能开一个返修卡）*/
        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "返修批次工步";
        row["Value"] = string.Format("{0}{1}", drFc["ContainerID"].ToString(), drPage["stepInfoID"].ToString());
        attributeDt.Rows.Add(row);
        /*返修主批次ID*/
        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "返修主批次ID";
        row["Value"] = drFc["ContainerID"].ToString();
        attributeDt.Rows.Add(row);
        /*返修主批次的工步ID*/
        row = attributeDt.NewRow();
        row["ContainerName"] = containerInfo.ContainerName;
        row["Level"] = containerInfo.Level;
        row["Name"] = "返修工步ID";
        row["Value"] = drPage["stepInfoID"].ToString();
        attributeDt.Rows.Add(row);
        //如果是通用子工艺开卡，则记录父工艺信息
        if (isSub)
        {
            row = attributeDt.NewRow();
            row["ContainerName"] = containerInfo.ContainerName;
            row["Level"] = containerInfo.Level;
            row["Name"] = "无订单开卡父工艺ID";
            row["Value"] = drPage["WorkflowID"].ToString();
            attributeDt.Rows.Add(row);

            row = attributeDt.NewRow();
            row["ContainerName"] = containerInfo.ContainerName;
            row["Level"] = containerInfo.Level;
            row["Name"] = "无订单开卡父工序ID";
            row["Value"] = drPage["startWorkflowStep"].ToString();
            attributeDt.Rows.Add(row);
        }
        return attributeDt;
    }



    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


}